<template>
	<el-upload
    class="upload-demo"
    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,.csv,text/plain,application/pdf,application/x-zip-compressed,application/octet-stream"
    :action="action"
    :data.sync="dataForm"
    :before-upload="beforeUpload"
    :on-success="uploadOnSuccess"
    :on-preview="handlePreview"
    :before-remove="beforeRemove"
    :file-list="fileList"
    :disabled="!displayBtn">
    <el-button size="mini" type="primary" v-if="displayBtn">点击上传</el-button>
    <!-- {{linkTable}}
    {{linkId}}
    {{linkField}} -->
  </el-upload>
</template>

<script>
export default {
  name: 'upload-file',
  props: {
    fileList: {
      type: Array,
      default () {
        return []
      }
    },
    linkTable: String,
    linkId: String,
    linkField: String,
    displayBtn: Boolean
  },
  data () {
    return {
      action: this.$http.requestUrl('/common/attachment/upload'),
      dataForm: {
        token: `${this.$cookie.get('token')}`,
        linkTable: this.linkTable,
        linkId: this.linkId,
        linkField: this.linkField
      }
    }
  },
  methods: {
    beforeUpload (file) {
      // alert('this.dataForm.linkId' + this.dataForm.linkId)
      // alert('this.linkId' + this.linkId)
      this.dataForm.linkId = this.linkId
      const isLt30M = file.size / 1024 / 1024 < 30
      if (!isLt30M) {
        this.$message.error('单个文件大小不能超过30MB!')
      }
      return isLt30M
    },
    uploadOnSuccess (e, file) {
      // console.log(JSON.stringify(file))
      // 上传附件
      this.pass = true
      this.$message.success('上传成功')
      this.fileList.push({
        id: file.response.id,
        url: file.url,
        name: file.name.split('.')[0]
      })
    },
    beforeRemove (file, i) {
      // console.log(JSON.stringify(file))
      if (!file.url) {
        return false
      }
      return this.$confirm('是否删除此附件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        this.$http({
          url: this.$http.requestUrl('/common/attachment/delete'),
          method: 'post',
          data: file.id
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功',
              onClose: () => {
                this.fileList.splice(i, 1)
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    handlePreview (file) {
      // console.log(file)
      window.open(file.url)
    }
  }
}
</script>

<style>
</style>
